import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';

// 模拟用户数据
const mockUsers = [
  {
    id: 1,
    username: 'teacher1',
    password: '123456',
    name: '张老师',
    role: 'teacher',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  },
  {
    id: 2,
    username: 'student1',
    password: '123456',
    name: '李同学',
    role: 'student',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  },
  {
    id: 3,
    username: 'admin',
    password: 'admin',
    name: '管理员',
    role: 'admin',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  }
];

export const useUserStore = defineStore('user', () => {
  const router = useRouter();
  const currentUser = ref(null);
  const token = ref('');
  
  // 判断用户是否已登录
  const isLoggedIn = computed(() => !!token.value);
  
  // 判断用户角色
  const isTeacher = computed(() => currentUser.value?.role === 'teacher');
  const isStudent = computed(() => currentUser.value?.role === 'student');
  const isAdmin = computed(() => currentUser.value?.role === 'admin');
  
  // 登录方法
  function login(username, password) {
    return new Promise((resolve, reject) => {
      // 模拟API请求
      setTimeout(() => {
        const user = mockUsers.find(
          (u) => u.username === username && u.password === password
        );
        
        if (user) {
          currentUser.value = user;
          token.value = `token-${user.id}-${Date.now()}`;
          localStorage.setItem('token', token.value);
          localStorage.setItem('user', JSON.stringify(user));
          resolve(user);
        } else {
          reject(new Error('用户名或密码错误'));
        }
      }, 300);
    });
  }
  
  // 退出登录
  function logout() {
    currentUser.value = null;
    token.value = '';
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    router.push('/login');
  }
  
  // 从本地存储恢复用户会话
  function restoreSession() {
    const savedToken = localStorage.getItem('token');
    const savedUser = localStorage.getItem('user');
    
    if (savedToken && savedUser) {
      token.value = savedToken;
      currentUser.value = JSON.parse(savedUser);
      return true;
    }
    
    return false;
  }
  
  // 获取用户权限
  const getUserPermissions = computed(() => {
    if (!currentUser.value) return [];
    
    // 根据角色返回不同的权限
    switch (currentUser.value.role) {
      case 'admin':
        return ['home', 'students', 'courses', 'grades', 'users', 'roles'];
      case 'teacher':
        return ['home', 'students', 'courses', 'grades'];
      case 'student':
        return ['home', 'courses', 'grades', 'course-selection'];
      default:
        return [];
    }
  });
  
  return {
    currentUser,
    token,
    isLoggedIn,
    isTeacher,
    isStudent,
    isAdmin,
    login,
    logout,
    restoreSession,
    getUserPermissions
  };
});